import { Controller, Get, Post, Body, Query, Session, Req } from '@nestjs/common';
import { PermissionService } from './permission.service';

@Controller('permission')
export class PermissionController {
  constructor(private readonly permissionService: PermissionService) { }

  @Get('getPermission')
  async getPermission(@Query('robotId') robotId: string, @Session() session: Record<string, any>, @Req() req: any) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      const permissions = await this.permissionService.findAll(parseInt(robotId, 10));
      return {
        code: 0,
        data: permissions,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('createPermission')
  async createPermission(@Body() createPermissionDto: any, @Session() session: Record<string, any>, @Req() req: any) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      const permission = await this.permissionService.create(createPermissionDto);
      return {
        code: 0,
        data: permission,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('removePermission')
  async removePermission(@Body() body: { id: number }, @Session() session: Record<string, any>, @Req() req: any) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      await this.permissionService.remove(body.id);
      return {
        code: 0,
        data: null,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }
} 